package com.yonyou.cyxdms.basedata.client.service.basedata;

import com.yonyou.cyx.framework.bean.dto.base.ClientInfoDTO;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.ModelCacheVO;
import com.yonyou.cyxdms.basedata.client.dto.VsProductDlrVO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.util.ConditionMapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 车型信息
 *
 * @author: renwd
 * @since: 2018/11/29
 * @version:1.0 Copyright: Copyright (c) 2018
 */

@Service
public class BaseCommonModelServiceImpl implements BaseCommonModelService {

    private final Logger logger = LoggerFactory.getLogger(BaseCommonModelServiceImpl.class);

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 根据车型id查询车型信息
     *
     * @param modelId
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.ModelCacheVO
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public ModelCacheVO getValueByModelId(String modelId) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODELID, loginInfoDto.getAppId());
        Object modelData = redisClient.hget(messageFormat, modelId);
        if (null == modelData) {
            // 重新加载这个id值的数据
            Map<String, Object> stringObjectMap = ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), null);
            stringObjectMap.put("modelId", modelId);
            loadValueIfNotExists(stringObjectMap, messageFormat);
            Object redisModelData = redisClient.hget(messageFormat, modelId);
            if (null == redisModelData) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisModelData), ModelCacheVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(modelData), ModelCacheVO.class);
        }
    }

    /**
     * 查询数据
     *
     * @param queryByMap 查询条件
     * @author renwd
     * @since 2018/11/30
     */
    private void loadValueIfNotExists(Map<String, Object> queryByMap, String messageFormat) {
        List<ModelCacheVO> modelDtoResponse = baseDataCommonClient.queryModelBySql(queryByMap).getData();
        logger.info("feign查询Model信息:{}", modelDtoResponse);

        if (!CommonUtils.isNullOrEmpty(modelDtoResponse)) {
            modelDtoResponse.stream().forEach(modelCacheDto -> initOneValue(modelCacheDto, messageFormat));
        }
    }

    /**
     * 数据放置redis
     *
     * @param modelCache
     * @author renwd
     * @since 2018/11/30
     */
    private void initOneValue(ModelCacheVO modelCache, String key) {
        redisClient.hsetExpire(key, String.valueOf(modelCache.getModelId()), JSONUtil.objectToJson(modelCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    @Override
    public List<ModelCacheVO> allModel() {
        return baseDataCommonClient.allModel().getData();
    }

    /**
     * 查询租户下的经销商下的所有车型
     *
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.ModelCacheVO>
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public List<ModelCacheVO> listAllModel() {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        Object modelData = redisClient.get(messageFormat);
        if (null == modelData) {
            List<ModelCacheVO> modelDtoResponse = baseDataCommonClient.queryModelBySql(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode())).getData();
            logger.info("feign查询Model信息:{}", modelDtoResponse);

            if (!CommonUtils.isNullOrEmpty(modelDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(modelDtoResponse), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisModelData = redisClient.get(messageFormat);

            if (null == redisModelData) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisModelData), ModelCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(modelData), ModelCacheVO.class);
        }
    }

    /**
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<ModelCacheVO> getAllModelByAppId(String appId) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL__APPID_ALL, appId);
        //ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        Object modelDto = redisClient.get(messageFormat);
        if (null == modelDto) {
            // 查询所有数据
            List<ModelCacheVO> modelDtoResponse = baseDataCommonClient.getAllModelByAppId(appId).getData();
            logger.info("feign查询series信息:{}", modelDtoResponse);
            if (!CommonUtils.isNullOrEmpty(modelDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(modelDtoResponse),
                        BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisModelDto = redisClient.get(messageFormat);
            if (null == redisModelDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisModelDto), ModelCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(modelDto), ModelCacheVO.class);
        }
    }

    @Override
    public VsProductDlrVO getModelNew(String modelCode,String appId) {
        return baseDataCommonClient.getModelNew(modelCode,appId).getData();
    }
}
